﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ResetPage();
        string act = this.Request.Params["act"];
        switch (act)
        {
            case "dk": panelDangKiTaiKhoan.Visible = true; DocNoiQuy();
                break;
            case "bs": BasicSearchAction();
                break;
            case "as": panelAdvanceSearch.Visible = true;
                break;
            case "1":
                break;
        }

    }

    private void BasicSearchAction()
    {
        panelBasicSearch.Visible = true;
        if(PreviousPage!=null)
            if (PreviousPage.IsCrossPagePostBack)
            {
                txtTenSanPham.Text = ((TextBox)PreviousPage.Master.FindControl("txtSearchKey")).Text;
                DoBasicSearch();
            }
    }

    private void ResetPage()
    {
        panelBasicSearch.Visible = false;
        panelDangKiTaiKhoan.Visible = false;
    }

    #region Register
    private void DangKi()
    {
        DocNoiQuy();
    }

    private void DocNoiQuy()
    {
        StreamReader StreamReader1 = new StreamReader(Server.MapPath("~/")+"noiquy.txt");
        txtNoiQuy.Text = StreamReader1.ReadToEnd();
        StreamReader1.Close();
    }

    protected void UserRegister(object sender, EventArgs e)
    {
        string hoTen = txtHoTen.Text;
        string userName = txtTenDangNhap.Text;
        string matKhau1 = txtMatKhau1.Text;
        string matKhau2 = txtMatKhau2.Text;        
        string sdt = txtSoDienThoai.Text;
        
        if (matKhau1 == matKhau2)
        {
            if (userName != "")
            {
                if (InsertToTAIKHOAN(userName, matKhau1))
                {
                    string userid = GetNewUserID().ToString();
                    if (InsertToTHONGTINTK(userid, hoTen, sdt))
                    {
                        lbMsg.Text = "Đăng kí tài khoản thành công.";
                        panelDangKiTaiKhoan.Visible = false;
                    }
                    else
                        lbMsg.Text = "Rất tiếc. Có điều gì đó đã hoạt động không đúng. Xin vui lòng thử lại sau. (er1)";
                }
                else
                    lbMsg.Text = "Rất tiếc. Có điều gì đó đã hoạt động không đúng. Xin vui lòng thử lại sau. (er2)";
            }
            else
                lbMsg.Text = "Nhập tên đăng nhập.";
        }
        else
            lbMsg.Text = "Sai mật khẩu.";
    }


    private bool InsertToTAIKHOAN(string userName, string matKhau)
    {
        string qInsert = "insert into TAIKHOAN(TenTaiKhoan,MatKhau,MaLoaiTaiKhoan) values ('" + userName + "','" + matKhau + "',1)";
        SqlCommand cmd = new SqlCommand(qInsert, Helper.ConnectToDataBase());
        int re = cmd.ExecuteNonQuery();
        if (re != -1)
            return true;
        else
            return false;
    }

    private bool InsertToTHONGTINTK(string userid, string hoTen, string sdt)
    {
        string qInsert = "insert into THONGTINTAIKHOAN(HoTen,SoDienThoai,MaTaiKhoan) values (N'" + hoTen + "','" + sdt +"',"+userid+")";
        SqlCommand cmd = new SqlCommand(qInsert, Helper.ConnectToDataBase());
        int re = cmd.ExecuteNonQuery();
        if (re != -1)
            return true;
        else
            return false;
    }

    private int GetNewUserID()
    {
        string qSelectMSP = "SELECT TOP 1 MaTaiKhoan FROM TAIKHOAN ORDER BY MaTaiKhoan DESC";
        SqlCommand cmd = new SqlCommand(qSelectMSP, Helper.ConnectToDataBase());
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader != null)
        {
            reader.Read();
            return reader.GetInt32(0);
        }

        Helper.DisposeCommand(ref cmd);
        return -1;
    }
    #endregion

    #region Search
    protected void BasicSearch(object sender, EventArgs e)
    {
        DoBasicSearch();
    }

    private void DoBasicSearch()
    {
        string tsp = GetStringKey();
        string qSelect = "select c.TenTaiKhoan,TenSanPham,MaSanPham,NgayHetHan,GiaHienTai,HinhAnh,a.MaTaiKhoan from SANPHAM a, TAIKHOAN c where TenSanPham like '" + tsp + "' and c.MaTaiKhoan=a.MaTaiKhoan" + GetAdvanceQuery() + " order by NgayHetHan desc";
        SqlCommand cmd = new SqlCommand(qSelect, Helper.ConnectToDataBase());
        try
        {
            rptProducts.DataSource = cmd.ExecuteReader();
            rptProducts.DataBind();
            if (rptProducts.Items.Count == 0)
                lbStatus.Text = "Không tìm thấy kết quả.";
            else
                lbStatus.Text = "";
            Helper.DisposeCommand(ref cmd);
        }
        catch (Exception)
        {
            Helper.DisposeCommand(ref cmd);
        }
        panelSanPham.Visible = true;
    }

    private string GetAdvanceQuery()
    {
        string str = "";
        if (panelAdvanceSearch.Visible==true)
        {
            if (TryIntParse(txtGiaTu.Text))
                str += " and GiaKhoiDiem>="+int.Parse(txtGiaTu.Text).ToString();

            if (TryIntParse(txtGiaDen.Text))
                str += " and GiaHienTai<=" + int.Parse(txtGiaDen.Text).ToString();

            if (TryDateTimeParse(txtNgayDang1.Text))
                str += " and DATEDIFF(day,NgayDang,'" + lbnd1.Text +"')<=0";
            if (TryDateTimeParse(txtNgayDang2.Text))
                str += " and DATEDIFF(day,NgayDang,'" + lbnd2.Text + "')>=0";

            if (TryDateTimeParse(txtNgayHetHan1.Text))
                str += " and DATEDIFF(day,NgayHetHan,'" + lbnhh1.Text + "')<=0";
            if (TryDateTimeParse(txtNgayHetHan2.Text))
                str += " and DATEDIFF(day,NgayHetHan,'" + lbnhh2.Text + "')>=0";

            if (DropDownListLoaiSanPham.SelectedIndex > 0)
                str += " and MaLoaiSanPham="+DropDownListLoaiSanPham.SelectedIndex.ToString();

        }
        return str;
    }

    private bool TryIntParse(string value)
    {
        try
        {
            int.Parse(value);
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }

    private bool TryDateTimeParse(string value)
    {
        try
        {
            DateTime.Parse(value);
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }

    private string GetStringKey()
    {
        string key = txtTenSanPham.Text;
        key = "%" + key + "%";
        key = key.Replace(' ', '%');
        return key;
    }

    protected void Toogle(object sender, EventArgs e)
    {
        SetToogle(!panelAdvanceSearch.Visible);
    }

    private void SetToogle(bool b)
    {
        panelAdvanceSearch.Visible = b;
        if (b == true)
        {
            btToggle.Text = "Tìm kiếm cơ bản";
            InitAdvanceSearch();
        }
        else
            btToggle.Text = "Tìm kiếm nâng cao";
    }

    private void InitAdvanceSearch()
    {
        LoadLoaiSanPham();
        //calendarSearch.SelectedDay = DateTime.MinValue;
        calendarSearch.Visible = false;
    }

    private void LoadLoaiSanPham()
    {
        DropDownListLoaiSanPham.SelectedIndex = -1;
        if (DropDownListLoaiSanPham.Items.Count > 2)
            return;
        string query = "select MaLoaiSanPham, TenLoaiSanPham from LOAISANPHAM";
        SqlCommand cmd = new SqlCommand(query, Helper.ConnectToDataBase());
        DropDownListLoaiSanPham.DataSource = cmd.ExecuteReader();
        DropDownListLoaiSanPham.DataTextField = "TenLoaiSanPham";
        DropDownListLoaiSanPham.DataValueField = "MaLoaiSanPham";
        DropDownListLoaiSanPham.DataBind();
        Helper.DisposeCommand(ref cmd);
    }

    protected void AdvanceSearch(object sender, EventArgs e)
    {
    }

    protected void ShowCalNgayDang1(object sender, EventArgs e)
    {
        lbTxtFlag.Text = "11";
        calendarSearch.Visible = true;
    }

    protected void ShowCalNgayDang2(object sender, EventArgs e)
    {
        lbTxtFlag.Text = "12";
        calendarSearch.Visible = true;
    }
    
    protected void ShowCalHetHan1(object sender, EventArgs e)
    {
        lbTxtFlag.Text = "21";
        calendarSearch.Visible = true;
    }

    protected void ShowCalHetHan2(object sender, EventArgs e)
    {
        lbTxtFlag.Text = "22";
        calendarSearch.Visible = true;
    }

    protected void ResetSearchForm(object sender, EventArgs e)
    {
        txtTenSanPham.Text = "";
        lbTxtFlag.Text = "";
        txtGiaTu.Text = "";
        txtGiaDen.Text = "";
        txtNgayDang1.Text = "";
        txtNgayDang2.Text = "";
        txtNgayHetHan1.Text = "";
        txtNgayHetHan2.Text = "";
        DropDownListLoaiSanPham.SelectedIndex = 0;
        calendarSearch.Visible = false;
        rptProducts.DataSource = null;
        rptProducts.DataBind();
    }
    

    protected void CalendarSelection(object sender, EventArgs e)
    {
        switch (lbTxtFlag.Text)
        {
            case "11": 
                txtNgayDang1.Text = calendarSearch.SelectedDate.ToString("dd/MM/yyyy");
                lbnd1.Text = calendarSearch.SelectedDate.ToString("s");
                break;
            case "12":
                txtNgayDang2.Text = calendarSearch.SelectedDate.ToString("dd/MM/yyyy");
                lbnd2.Text = calendarSearch.SelectedDate.ToString("s");
                break;
            case "21": 
                txtNgayHetHan1.Text = calendarSearch.SelectedDate.ToString("dd/MM/yyyy");
                lbnhh1.Text = calendarSearch.SelectedDate.ToString("s");
                break;
            case "22":
                txtNgayHetHan2.Text = calendarSearch.SelectedDate.ToString("dd/MM/yyyy");
                lbnhh2.Text = calendarSearch.SelectedDate.ToString("s");
                break;
        }
        calendarSearch.Visible = false;
    }
    #endregion
}
